package com.devoteam.shacts;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Shacts extends Activity {
	
	private final Context context = this;
	
	private static Cursor vCursor = null;
	
	//this activity ID
	private static final int REQUEST_SCAN = 2;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Button buttonShare = (Button) findViewById(R.id.button_share);
		Button buttonScan = (Button) findViewById(R.id.button_scan);

		buttonShare.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				ContentResolver cr = getContentResolver();
				//We get a cursor on the contacts alphabetically sorted by name
				vCursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME+" COLLATE NOCASE");
				//let's start a display activity of the contact list 
				Intent i = new Intent(context, ShareContacts.class);
				context.startActivity(i);
			}
		});
		
		buttonScan.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//we start the barcode scanner scanning activity 
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
				try {
					//we identify the request with REQUEST_SCAN
					startActivityForResult(intent, REQUEST_SCAN);
				} catch (ActivityNotFoundException e) {
					//If barcode scanner is not installed
					Toast.makeText(context, context.getString(R.string.er_barcode), Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	
	//method called on the result of an activity started from this context
	public void onActivityResult(int reqCode, int resCode, Intent intent) {
		//if it's the scan result
		if (REQUEST_SCAN == reqCode) {
			if (RESULT_CANCELED == resCode) {
				Toast.makeText(this, this.getString(R.string.scan_canceled), Toast.LENGTH_LONG).show();
			}else{
				//we get the vcdard as a string
				String contents = intent.getStringExtra("SCAN_RESULT");
				try{
					//we start the contact insertion activity
					startActivity(VCardFactory.makeVCardIntent(contents));
				}catch(Exception e){
					Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
				}
			}
		}
	}
	
	public static Cursor getVCursor(){
		return vCursor;
	}
}